package cn.wolfcode.rbac.web.intercptor;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.query.RequiredPermission;
import cn.wolfcode.rbac.util.CurrentUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

@Component
public class SecurityInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Employee current = CurrentUtil.getCurrent();
        if(current.isAdmin()){
            return true;
        }


        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiredPermission methodAnnotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        if(methodAnnotation == null){
            return true;
        }


        Set<String> expression = CurrentUtil.getExpression();
        if(expression.contains(methodAnnotation.value()[1])){
            return true;
        }

        request.getRequestDispatcher("/views/common/nopermission.jsp").forward(request,response);
        return false;
    }
}
